"""
自动修复agent脚本。
"""
# coding=utf-8
import os
import sys
import time


class Auto:
    def __init__(self):
        self.zabbix_command = '/etc/zabbix/bin'
        self.agent_config = '/etc/zabbix/zabbix_agentd.conf'
        self.log = '/root/zabbix.log'

        self.exe_flow = ['version', 'ping', 'is_enable', 'exist_bak', 'copy_config', 'set_config', 'run']
        self.command = {
            'version': "cat /etc/redhat-release",
            'ping': ['ping -c 1 172.23.6.11', 'ping -c 1 172.16.6.92'],
            'is_enable': {'6': 'chkconfig --list | grep zabbix-agent > /dev/null',
                          '7': 'systemctl -a | grep zabbix-agent > /dev/null'},
            'exist_bak': '[ -e {0} ]'.format(self.agent_config + '.bak'),
            'copy_config': 'cp {0} {1}'.format(self.agent_config, self.agent_config + '.bak'),
            'set_config': 'cat {0}'.format(self.agent_config),
            'run': {
                'kill': 'pidof zabbix_agentd | xargs kill > /dev/null',
                '6': 'service zabbix-agent start > /dev/null',
                '7': 'systemctl start zabbix-agent > /dev/null',
                'command': 'zabbix_agentd -c {0}'.format(self.agent_config)},
            'log': '[ -e {0} ]'.format(self.log)
        }
        self.result = {
            'version': '',
            'ping': '',
            'is_enable': '',
            'exist_bak': '',
            'copy_config': '',
            'set_config': '',
            'run': '',
            'hostname': ''
        }

    def exe_command(self):
        """
        指定所有指定流程的命令。
        :return:
        """
        for exe in self.exe_flow:
            if exe == 'version':
                iterable = os.popen(self.command[exe])
                for line in iterable:
                    if '.' in line:
                        lines = line.split(' ')
                        for l in lines:
                            if '.' in l:
                                self.result[exe] = l[0:1]
                                break
                        break
                else:
                    self.result[exe] = 'fail'
            elif exe == 'ping':
                for ip in self.command[exe]:
                    if os.system(ip + ' > /dev/null') == 0:
                        self.result[exe] = ip.split(' ')[3]
                        break
                else:
                    self.result[exe] = 'fail'
            elif exe == 'is_enable':
                version = self.result['version']
                if version:
                    if os.system(self.command[exe][version]) == 0:
                        self.result[exe] = 'ok'
                    else:
                        self.result[exe] = 'fail'
            elif exe == 'exist_bak':
                if os.system(self.command[exe]) == 0:
                    self.result[exe] = 'ok'
                else:
                    self.result[exe] = 'fail'
            elif exe == 'copy_config':
                if self.result['exist_bak'] == 'fail':
                    os.system(self.command[exe])
            elif exe == 'set_config':
                if self.result['ping'] != '' and self.result['ping'] != 'fail':
                    txt = []
                    with open(self.agent_config) as r:
                        for line in r:
                            txt.append(line)
                    for n, line in enumerate(txt):
                        if 'ServerActive=' in line:
                            txt[n] = 'ServerActive=' + self.result['ping'] + '\n'
                            continue
                        if 'Hostname=' in line:
                            for t_line in txt:
                                if 'Hostname' in t_line and  'auto' in t_line:
                                    break
                            else:
                                _name = 'auto_' + str(time.time())
                                txt[n] = 'Hostname=' + _name + '\n'
                                self.result['hostname'] = _name
                        if 'HostMetadata=' in line:
                            txt[n] = 'HostMetadata=' + 'Centos_' + self.result['version'] + '_auto' + '\n'
                            continue
                    with open(self.agent_config, 'w') as w:
                        for line in txt:
                            w.write(line)
                    self.result[exe] = 'ok'
                else:
                    self.result[exe] = 'fail'
            elif exe == 'run':
                os.system(self.command[exe]['kill'])
                # index = None
                # if self.result['version'] == '6':
                #     index = '6'
                # elif self.result['version'] == '7':
                #     index = '7'
                if os.system(self.command[exe][self.result['version']]) == 0:
                    self.result[exe] = 'ok'
                else:
                    # if self.result['exist_bak'] == 'ok':
                    if os.system(self.command[exe]['command']) == 0:
                        self.result[exe] = 'ok'
                    else:
                        self.result[exe] = 'fail'

    def check_log(self):
        """
        检查日志文件之前运行的状态。
        :return:
        """
        if self.command['log'] == 0:
            with open(self.log) as r:
                for line in r:
                    if 'run' in line:
                        if line.split('=')[1] == 'ok':
                            print('exit')
                            sys.exit()

    def write_log(self):
        with open(self.log, 'w') as w:
            for key in self.result.keys():
                w.write(key + '=' + self.result[key] + '\n')

    def run(self):
        self.check_log()
        self.exe_command()
        self.write_log()


def main():
    auto = Auto()
    auto.run()
    print(auto.result)


if __name__ == "__main__":
    args = sys.argv
    if len(args) == 2:
        if args[1] == '241' + '000':
            main()

